/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.synjones.pay.model.context;

import com.synjones.core.util.Charsets;
import com.synjones.core.util.MapUtil;
import java.util.Map;

/**
 * abstract context
 *
 * @author zhzy
 */
public abstract class AbstractContext implements IContext {

    private final HashMapCaseInsensitive<Object> _context;

    private final String[] _splitCharacter = new String[]{"&"};

    protected AbstractContext(Map<String, Object> map) {
        this._context = new HashMapCaseInsensitive<>(map);
    }

    protected AbstractContext(String queryString) {
        this._context = new HashMapCaseInsensitive<>();
        String[] s = split(queryString);

        for (String ss : s) {
            int i = ss.indexOf('=');
            if (i > 0 && i < ss.length()) {
                this._context.put(ss.substring(0, i), ss.substring(i + 1));
            }
        }
    }

    /*
	 * 将查询串分割成key,value值对 默认的查询串格式是：key=value&key1=value1... 继承类可以覆盖此方法
     */
    private String[] split(String str) {
        if (str == null || str.length() == 0) {
            return new String[]{};
        }

        StringBuilder sb = new StringBuilder();
        for (String s : this._splitCharacter) {
            if (sb.length() > 0) {
                sb.append('|');
            }
            sb.append(s);
        }

        return str.split(sb.toString());
    }

    @Override
    public synchronized void add(String key, Object value) {
        this._context.put(key, value);
    }

    @Override
    public synchronized void addAll(Map<String, Object> map) {
        this._context.putAll(map);
    }

    @Override
    public <T extends Object> T get(String key) {
        if(_context.containsKey(key)){
            return (T)_context.get(key);
        }
        return null;
    }

    @Override
    public String toQueryString(String[] exclude) {
        return MapUtil.toQueryString(_context, exclude, false, Charsets.UTF_8.name());
    }
    
}
